<template>
  <div class="flex-1 bg-light-100 flex flex-col" >
    <div class="flex justify-between py-1">
      <div>
        <el-dropdown  trigger="click">
          <span class="el-dropdown-link">
            <div class="icon-btn wh-6! ml-2 i-carbon-face-satisfied "></div>
          </span>
          <template #dropdown>
            <div class="expressions-list">
              <div :key="item._id" v-for="item in picList" @click="emitPic(item)" class="expressions">
                <img  class="cursor-pointer" :src="IMG_URL_SERVER +item?.url" :alt="item?.name">
              </div>

            </div>
          </template>
        </el-dropdown>

        <el-upload  
          ref="uploadRef"
          class="upload-demo inline-block"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="submitUpload"
        >
          <div  class="icon-btn wh-6! ml-2 i-carbon-image "></div>
        </el-upload>
        
      </div>
    </div>

    <div class="input-area">
      <el-scrollbar>
        <div ref="editor"  @input="edit"  contenteditable="true" data-text="请输入内容..." @paste.capture="pasting" class="input-div" >
        </div>
      </el-scrollbar>
    </div>
    <div class="flex justify-end items-center flex-1">
      <div class="limit mr-2">
          <span>{{textLen}}</span> / <span>1000</span>
      </div>
      <button class="btn submit mr-2 " @click="submit">发送</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { UploadInstance } from 'element-plus'
import { fetchUpload,fetchExpressions } from '@/server';
import { IMG_URL_SERVER } from "@/config"
import { useSocketStore } from "@/store"
import { storeToRefs } from 'pinia'


//聊天socket
const socket = inject<any>('socket')
//现在登录用户store
const authStore = useAuthStore()
const { user } = storeToRefs(authStore)
//route 
const route = useRoute()
//帖子长度
const textLen = ref(0)
//编辑器dom
const editor:any = ref()
//上传图标dom
const uploadRef = ref<UploadInstance>()
//图片列表
const picList = ref()
//socketStore
const socketStore = useSocketStore()




const submit = ()=>{
  
  if(editor.value.innerHTML == ''){
    return false;
  }
  //自己发送的socket信息
  socket.once('pushMsg', async (data: any) => {
    if (user.value._id === data.from._id) {
      socketStore?.chatContent?.push(data)
    }
    await nextTick()
    socketStore?.scrollBar?.value?.setScrollTop(socketStore?.chatBox?.value.scrollHeight)
  })
  socket.emit('sendMsg',{
    from: authStore?.user?._id,
    to: route?.params?.id,
    message: editor?.value?.innerHTML
  })

  
  editor.value.innerHTML = ''
}





//修改时侦听
const edit = ()=>{
  textLen.value = editor.value.innerText.length
}


// 监听粘贴事件
function pasting(event:any) {
  textLen.value = editor.value.innerText.length
  //文字粘贴
  // let txt = event.clipboardData.getData('Text')
  // console.log(event.clipboardData.getData('Text'))
  // if(typeof(txt) == 'string') {
  //   // 注意代码注入，这代码不会有问题
  //   editor.value.insertAdjacentText("beforeend",txt)
  // }

  const items = (event.clipboardData || window.Clipboard).items


  for (let i = 0; i < items.length; i++) {
    if (items[i].type.indexOf('image') !== -1) {
      event.preventDefault()
      return false
    }
  }
  
  //图片粘贴
  // let file = null
  // if(items.length) {
  //   for (let i = 0; i < items.length; i++) {
  //       if (items[i].type.indexOf('image') !== -1) {
  //           file = items[i].getAsFile()
  //           handleChange(file)
  //           break
  //       }
  //   }
  // }
}
//提交图片
const submitUpload = (file:any) => {
  handleChange(file)
}
// 图片上传
function handleChange(file:any, fileList?:any) {
    let formData = new FormData()
    formData.append('topicImg', file.raw || file)
    fetchUpload(formData).then( img => {
        editor.value.insertAdjacentHTML("beforeend",`<img style="display: inline-block;vertical-align:text-bottom;max-width:90%;" src="${img.url}" alt="${img.name}">`) 

        // if(fileList){
        //   fileList.push(obj)
        //   console.log(fileList) 
        // }    
    })
}

//表情按钮点击发送图片到编辑器
const emitPic = (img:any)=>{
  editor.value.insertAdjacentHTML("beforeend", `<img style="display: inline-block;width: 4rem;height: 4rem;vertical-align:text-bottom;" src="${IMG_URL_SERVER+img.url}" alt="${img.name}">`)
}

watchEffect(()=>{
  fetchExpressions(()=>true).then((data)=>{
    picList.value = data
  })

})


</script>

<style scoped lang="scss">
.submit{
  background: linear-gradient(to right top, #65dfc9,#6cbdeb);
  transition: all 0.2s;
  box-shadow: 2px 3px 5px rgba($color: #000, $alpha: 0.15),-2px -3px 5px rgba($color: #000, $alpha: 0.15);
  &:hover{
    background: linear-gradient(to right top, #6ff5dc,#8cd0f7);
    box-shadow:inset 2px 3px 5px rgba($color: #fafafa, $alpha: 0.15),inset -2px -3px 5px rgba($color: #fafafa, $alpha: 0.15);

  }
  &:active{
    background: linear-gradient(to right top, #6ff5dc,#8cd0f7);
    box-shadow:inset 2px 3px 5px rgba($color: #fafafa, $alpha: 0.15),inset -2px -3px 5px rgba($color: #fafafa, $alpha: 0.15);

  }
}
.input-area{
    position: relative;
    overflow: hidden;
    height: 6.6rem;
    .input-div{
        vertical-align: text-bottom;
        background-color: #fff;
        border-top:1px solid #ccc;
        border-bottom:1px solid #ccc;
        outline: none;
        padding: 0.4rem;
        font-size: 0.9rem;
        transition: all 0.4s;
        height: auto;
        min-height: 6.6rem;
        max-height: 15rem;
        overflow-y: auto;
        word-wrap: break-word;

        &[contentEditable=true]:empty:not(:focus):before{
          content:attr(data-text);
          color:#aaa;
        }
        
        &:focus{
          border-top: 1px solid #31baf9;
          border-bottom: 1px solid #31baf9;
        }
    }
   .limit{
        position: absolute;
        right: 1rem;
        bottom: 1rem;
      }
}

.expressions-list{
  display: grid;
  padding: 4px;
  grid-template-columns: repeat(4,4rem);
  grid-template-rows: repeat(auto-fill,4rem);
  gap: 4px;
  height: 16rem;

  .expressions{
    display: inline-block;
    width: 4rem;
    height: 4rem;
    position: relative;
    img{
      width: 100%;
      height: 100%;
      object-fit: cover;
      position: absolute;
    }
  }
}
</style>